//
//  LMTabBarButton.m
//  李明微博
//
//  Created by apple on 15/12/4.
//  Copyright (c) 2015年 李明. All rights reserved.
//

#import "LMTabBarButton.h"
#import "LMBadgeView.h"

#define LMImageRidio 0.7


@interface LMTabBarButton()

@property (nonatomic,weak) LMBadgeView *badgeView;

@end

@implementation LMTabBarButton

// 重写高亮，取消高亮效果
- (void)setHighlighted:(BOOL)highlighted{}

-(LMBadgeView *)badgeView
{
    if (_badgeView == nil) {
        
        LMBadgeView *btn = [LMBadgeView buttonWithType:UIButtonTypeCustom];
        
        [self addSubview:btn];
        
        _badgeView = btn;
    }
    
    return _badgeView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    
    if(self = [super initWithFrame:frame])
    {
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
        self.imageView.contentMode = UIViewContentModeCenter;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        
        self.titleLabel.font = [UIFont systemFontOfSize:12];
        
    }
    return self;
}

-(void)setItem:(UITabBarItem *)item
{
    _item = item;
    
    [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
    
    [self addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:@"selectedImage" options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:@"badgeValue" options:NSKeyValueObservingOptionNew context:nil];
}


//属性发生变化就会调用这个方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    [self setTitle:_item.title forState:UIControlStateNormal];
    [self setImage:_item.image forState:UIControlStateNormal];
    [self setImage:_item.selectedImage forState:UIControlStateSelected];
    
    self.badgeView.badageValue = _item.badgeValue;
    
}


//修改子空间的frame 就是用的这个方法
-(void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat imageX = 0 ;
    CGFloat imageY = 0 ;
    CGFloat imageW = self.width ;
    CGFloat imageH = self.height * LMImageRidio;
    
    self.imageView.frame = CGRectMake(imageX , imageY, imageW, imageH);
    
    
    CGFloat titleX = 0 ;
    CGFloat titleY = imageH -3;
    CGFloat titleW = self.width;
    CGFloat titleH = self.height -titleY;
    self.titleLabel.frame = CGRectMake(titleX , titleY, titleW, titleH);
    
    self.badgeView.x = self.width-self.badgeView.width -10;
    self.badgeView.y = 0;
    
    
}
@end
